package com.egao.common.core.security;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import com.egao.common.core.Constants;
import com.egao.common.module.system.entity.User;
import com.egao.common.module.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
 * 用户登录验证Service
 * @author system
 */
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        RSA rsa = new RSA(Constants.RSA_PRIVATE_KEY, Constants.RSA_PUBLIC_KEY);
        byte[] decrypt = rsa.decrypt(username, KeyType.PrivateKey);
        String realUsername = StrUtil.str(decrypt, CharsetUtil.CHARSET_UTF_8);

        User user = userService.getByUsername(realUsername);
        if (user == null) {
            throw new UsernameNotFoundException("Username Not Found");
        }
        return userService.selectUserAuth(user);
    }



}